package org.zhss.demo.redis.hyperloglog;

import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/** 基于Hyperloglog的网站uv统计案例 */
public class HyperloglogUVDemo {

  private Jedis jedis = new Jedis("192.168.150.201");

  /** 初始化uv数据 */
  public void initUVdata() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String today = dateFormat.format(new Date());
    IntStream.range(0, 1358)
        .forEach(
            i -> {
              jedis.pfadd("hyperloglog_uv::" + today, String.valueOf(i + 1));
            });
  }

  /**
   * 获取当天的网站uv的值
   *
   * @return
   */
  public long getUV() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String today = dateFormat.format(new Date());
    return jedis.pfcount("hyperloglog_uv::" + today);
  }

  public static void main(String[] args) {
    HyperloglogUVDemo hyperloglogUVDemo = new HyperloglogUVDemo();
    hyperloglogUVDemo.initUVdata();
    long uv = hyperloglogUVDemo.getUV();
    System.out.println("今天的uv值：" + uv);
  }
}
